<?php


namespace services\dengta\robot;

use common\helpers\CommonHelper;
use common\models\marketing\OutpatientType;
use common\models\patient\HistoryRecord;
use common\models\patient\User;
use common\components\Service;
use Yii;


/**
 * Class WeChatService
 * @package services\robot
 */
class WechatService extends Service
{
    /**
     * 微信好友列表
     *
     * @param array $params [
     *       'wechatid' => '',// 微信ID
     *       'start_time' => '',// 开始时间【2020-01-01】
     *       'end_time' => '',// 结束时间【2020-01-01】
     *       'keywords' => '',// 关键词
     *       'is_reply' => '',// 是否未回复【1是、0全部】
     * ]
     * @return array
     */
//    public function getWechatContactListPage(array $params = [])
//    {
//        $params['keywords'] = trim($params['keywords'] ?? '');
//        $params['is_reply'] = $params['is_reply'] ?? 0;
//
//        $query = WechatContactinfo::find()->alias('a')
//            ->select(['a.id', 'a.wechatid', 'a.friendid', 'a.nickname', 'a.avatar', 'a.last_message_id', 'a.contact_time', 'a.state', 'a.remark_name'])
////            ->select(['a.*', 'MAX(b.create_time) message_create_time'])
////            ->leftJoin(WechatMessage::tableName().' b', "b.friendId = a.friendid AND b.wechatId = '".$params['wechat_id']."'")
//            ->where([
//                'a.wechatid' => $params['wechat_id'],
//                'a.state' => [WechatContactinfo::STATE_NORMAL, WechatContactinfo::STATE_DELETED, WechatContactinfo::STATE_BLOCKED]
//            ])
//            ->andWhere(['not like', 'a.friendid', '%chatroom', false]);// 排除群消息
//
//        if ($params['keywords']) {
//            $query->andWhere([
//                'or',
//                ['like', 'a.nickname', $params['keywords']],
//                ['like', 'a.friend_wechatno', $params['keywords']],
//            ]);
//        }
//
//        $order = [
////            'message_create_time' => SORT_DESC,
//            'a.create_time' => SORT_ASC,
//        ];
//
//        $data = $this->getListPageRes($query, 0, 0, $order);
//
//        // 今天
//        $nowDate = date('Y-m-d');
//        $nowDateTime = strtotime($nowDate);
//        $oneDateTime = $nowDateTime - 3 * 86400;// 1-3
//        $twoDateTime = $nowDateTime - 7 * 86400;// 4-7
//        $threeDateTime = $nowDateTime - 30 * 86400;// 8-30
//        $fourDateTime = $nowDateTime - 60 * 86400;// 30-60
//
//        $list = [
//            ['value' => '今天', 'total' => 0, 'child' => []],
//            ['value' => '1-3天', 'total' => 0, 'child' => []],
//            ['value' => '4-7天', 'total' => 0, 'child' => []],
//            ['value' => '8-30天', 'total' => 0, 'child' => []],
//            ['value' => '31-60天', 'total' => 0, 'child' => []],
//            ['value' => '60天以上', 'total' => 0, 'child' => []],
//            ['value' => '拉黑/删除', 'total' => 0, 'child' => []],
//        ];
//
//        $total = 0;
//
//        if ($params['is_reply']) {
//            // 查询
//            $condition = [
//                'ids' => array_column($data['list'], 'last_message_id'),
//            ];
//            $esService = new EsService();
//            $wechatMessageInfo = $esService->esSearch($condition);
//            $messageMap = [];
//            foreach ($wechatMessageInfo['list'] as $row) {
//                $messageMap[$row['id']] = $row;
//            }
//        }
//
//        foreach ($data['list'] as $row) {
//            $lastDate = $row['contact_time'] ?: '';
//            $lastDateTime = $lastDate ? strtotime($lastDate) : 0;
//
//            if ($params['is_reply']) {
//                $message = $messageMap[$row['last_message_id']] ?? [];
//
//                if ($message) {
//                    if ($message['issend'] == 'true') {
//                        continue;
//                    }
//                } else {
//                    continue;
//                }
//            }
//
//            $title = $row['remark_name'] ?: $row['nickname'];
//
//            $item = [
//                'id' => $row['id'],
////                'cid' => $row['cid'],
//                'wechatid' => $row['wechatid'],
//                'friendid' => $row['friendid'],
////                'friend_wechatno' => $row['friend_wechatno'],
//                'nickname' => $row['nickname'],
//                'remark_name' => $row['remark_name'],
//                'avatar' => $row['avatar'],
////                'message_cnt' => $messageCnt,// 聊天总数
//                'lats_create_time' => $lastDate,// 最近聊天时间
//            ];
//
//            if (in_array($row['state'], [WechatContactinfo::STATE_DELETED, WechatContactinfo::STATE_BLOCKED])) {
//                $index = 6;
//            } elseif ($lastDateTime >= $nowDateTime) {// 今天
//                $index = 0;
//            } elseif ($lastDateTime >= $oneDateTime && $lastDateTime < $nowDateTime) {// 1-3天
//                $index = 1;
//            } elseif ($lastDateTime >= $twoDateTime && $lastDateTime < $oneDateTime) {// 4-7天
//                $index = 2;
//            } elseif ($lastDateTime >= $threeDateTime && $lastDateTime < $twoDateTime) {// 8-30天
//                $index = 3;
//            } elseif ($lastDateTime >= $fourDateTime && $lastDateTime < $threeDateTime) {// 31-60天
//                $index = 4;
//            } else {// 60天以上
//                $index = 5;
//            }
//
//            $list[$index]['child'][] = $item;
//            $list[$index]['total'] += 1;
//            $total += 1;
//        }
//
//        foreach ($list as $key => $row) {
//            if (empty($row['child'])) {
//                continue;
//            }
//
//            $lastCreateTime = array_column($row['child'], 'lats_create_time');
//            array_multisort($lastCreateTime, SORT_DESC, $row['child']);
//
//            $list[$key]['child'] = $row['child'];
//        }
//
//        $data['list'] = $list;
//        $data['total'] = $total;
//
//        return $data;
//    }

    /**
     * 微信信息
     * Tips:
     *      存在微信线索则匹配微信线索，不存在则匹配患者绑定微信号。
     *      如果存在线索，想要匹配患者微信，则需先解绑线索微信。
     *      微信线索存在多个微信可能，能将多条线索转给同一个患者。
     *
     * @param int $id
     * @return array|mixed
     */
    public function wechatInfo(int $id = 0)
    {
        // 患者信息
        $patientUser = User::findOne($id);

        if ($patientUser && $patientUser->project_id != Yii::$app->params['project_id']) {
            return CommonHelper::api(422, '患者非当前项目');
        }

        if (empty($patientUser)) {
            $user = new User();
            $patientUser = $user->loadDefaultValues();
        }

        // 获取患者历史微信号
        $bindWechat = HistoryRecord::find()
            ->select('content')
            ->where([
                'patient_user_id' => $patientUser->id,
                'is_bind' => HistoryRecord::BIND_YES,
                'data_type' => HistoryRecord::DATA_TYPE_WECHAT
            ])->column();

        $bindWechatNoArr = $patientUser->wx_name ? array_diff($bindWechat, [$patientUser->wx_name]) : $bindWechat;

        $wechatNoArr = $patientUser->wx_name ? array_merge([$patientUser->wx_name], $bindWechat) : $bindWechat;
//        $nowWechat = [];
//        if (!empty($patientUser->wx_name)) {
//            $bindWechat[] = $patientUser->wx_name;
//            $nowWechat[] = $patientUser->wx_name;
//        }

        $data = CommonHelper::dengta_request('/v1/baiyou/wechat-bind-list', [], [
            'wechat_id' => $wechatNoArr,
//            'friendid' => $bindWechat,
            'bind_wechat' => $bindWechatNoArr
        ]);
//        $data = $this->getWechatList($bindWechat, $nowWechat);

        return [
            'list' => $data
        ];
    }

    /**
     * 解绑微信号
     */
    public function unbindWechat($id, $content)
    {
        // 解除微信号绑定
        HistoryRecord::updateAll(['is_bind' => HistoryRecord::BIND_NO], [
            'and',
            ['patient_user_id' => $id],
            ['content' => $content]
        ]);
    }

    /**
     * 获取微信信息,对应的,用户信息
     * @return array
     */
    public function getPatientWechatInfoByContent(string $friend_wechatno): array
    {
        $patientInfo = User::find()
            ->select('id, name as user_name, age, gender, outpatient_type_id')
            ->where([
                'project_id' => Yii::$app->params['project_id'],
                'wx_name' => $friend_wechatno,
                'status' => User::STATUS_ENABLE
            ])
            ->orderBy(['created_at' => SORT_DESC])
            ->asArray()
            ->one();


        if (empty($patientInfo)) {
            return [];
        }

        // 处理性别
        $patientInfo['gender_str'] = User::$genders[$patientInfo['gender']] ?? "";
        // 处理状态
        $patientInfo['status_name'] = OutpatientType::$outpatientType[$patientInfo['outpatient_type_id']] ?? "";

        return $patientInfo;
    }
}
